import json

import requests
from common.read import FileRead
from common.response import process_response
from common.log import logger
conf = FileRead().read_ini()
api_url = conf['url']['api_url']

class ApiNew:
    def __init__(self):
        self.api_url = api_url
        self.session = requests.session()
    # def do_request(self,uri,method,**kwargs):
    #     response = self.request(uri,method,**kwargs).json()
    #     logger.info("接口的返回内容>>>\n{}".format(json.dumps(response, ensure_ascii=False, indent=2)))


    def request(self,uri,method,**kwargs):
        self.request_log(uri,method,**kwargs)
        # if method == 'get':
        #     return requests.session().get(self.api_url+uri,**kwargs)
        # if method == 'post':
        #     return requests.session().post(self.api_url+uri,**kwargs)
        # if method == 'delete':
        #     return requests.session().delete(self.api_url+uri,**kwargs)
        # if method == 'put':
        #     return requests.session().put(self.api_url+uri,**kwargs)
        res = self.session.request(url = self.api_url + uri,method = method,**kwargs)
        return process_response(res)

    def request_log(self, uri, method, **kwargs):
        data = dict(**kwargs).get("data")
        json_data = dict(**kwargs).get("json")
        params = dict(**kwargs).get("params")
        headers = dict(**kwargs).get("headers")

        logger.info("接口请求的地址>>>{}".format(self.api_url + uri))
        logger.info("接口请求的方法>>>{}".format(method))
        if data is not None:
            logger.info("接口请求的data参数>>>\n{}".format(json.dumps(data, ensure_ascii=False, indent=2)))
        if json_data is not None:
            logger.info("接口请求的json参数>>>\n{}".format(json.dumps(json_data, ensure_ascii=False, indent=2)))
        if params is not None:
            logger.info("接口请求的params参数>>>\n{}".format(json.dumps(params, ensure_ascii=False, indent=2)))
        if headers is not None:
            logger.info("接口请求的headers参数>>>\n{}".format(json.dumps(headers, ensure_ascii=False, indent=2)))
